﻿<?php
define('PIGCMS_PATH', dirname(dirname(__FILE__)) . '/');
require_once PIGCMS_PATH . 'source/init.php';
$t_configs = D('Config')->field('`name`,`value`')->select();
foreach ($t_configs as $key => $value ) 
{
	$t_config[$value['name']] = $value['value'];
}
$_G['config'] = $t_config;
$action = ((isset($_GET['a']) ? addslashes($_GET['a']) : 'index'));
import('source.class.Wechat');
$wechat = new Wechat($t_config);
if ($action == 'index') 
{
	$data = $wechat->request();
	list($content, $type) = reply($data);
	if ($content) 
	{
		$wechat->response($content, $type);
	}
	else 
	{
		exit();
	}
}
else if ($action == 'get_ticket') 
{
	$data = $wechat->request();
	if (isset($data['InfoType'])) 
	{
		if ($data['InfoType'] == 'component_verify_ticket') 
		{
			if (isset($data['ComponentVerifyTicket']) && $data['ComponentVerifyTicket']) 
			{
				if ($config = D('Config')->where('`name`=\'wx_componentverifyticket\'')->find()) 
				{
					D('Config')->where('`name`=\'wx_componentverifyticket\'')->data(array('value' => $data['ComponentVerifyTicket']))->save();
				}
				else 
				{
					D('Config')->data(array('name' => 'wx_componentverifyticket', 'value' => $data['ComponentVerifyTicket'], 'type' => 'type=text', 'gid' => 0, 'tab_id' => 0))->add();
				}
				F('config', NULL);
				exit('success');
			}
		}
		else if ($data['InfoType'] == 'unauthorized') 
		{
			if (isset($data['AuthorizerAppid']) && $data['AuthorizerAppid']) 
			{
				$weixin_bind = D('Weixin_bind')->where('`authorizer_appid`=\'' . $data['AuthorizerAppid'] . '\'')->find();
				if (!empty($weixin_bind)) 
				{
					D('Weixin_bind')->where('`authorizer_appid`=\'' . $data['AuthorizerAppid'] . '\'')->delete();
					D('Store')->data(array('open_weixin' => '0'))->where(array('store_id' => $weixin_bind['store_id']))->save();
				}
				exit('success');
			}
		}
	}
}
function reply($data) 
{
	$user_name = $data['ToUserName'];
	$openid = $data['FromUserName'];
	$keyword = ((isset($data['Content']) ? $data['Content'] : ((isset($data['EventKey']) ? $data['EventKey'] : ''))));
	if ($data['ToUserName'] == 'gh_3c884a361561') 
	{
		if ($data['MsgType'] == 'event') 
		{
			return array($data['Event'] . 'from_callback', 'text');
		}
		if ($keyword == 'TESTCOMPONENT_MSG_TYPE_TEXT') 
		{
			return array('TESTCOMPONENT_MSG_TYPE_TEXT_callback', 'text');
		}
		if (strstr($keyword, 'QUERY_AUTH_CODE:')) 
		{
			$t = explode(':', $keyword);
			$query_auth_code = $t[1];
			$access_token = get_access_token($query_auth_code);
			$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
			$str = '{"touser":"' . $data['FromUserName'] . '", "msgtype":"text", "text":{"content":"' . $query_auth_code . '_from_api"}}';
			import('source.class.Http');
			Http::curlPost($url, $str);
		}
	}
	$weixin_bind = D('Weixin_bind')->where(array('user_name' => $user_name))->find();
	if ($data['MsgType'] == 'event') 
	{
		$id = $data['EventKey'];
		switch (strtoupper($data['Event'])) 
		{
			case 'SCAN': return weixin_scan($id, $data, $weixin_bind['store_id']);
			case 'CLICK': if ($menu = D('Diymenu_class')->where(array('store_id' => $weixin_bind['store_id'], 'title' => $id))->find()) 
			{
				switch ($menu['type']) 
				{
					case 0: return array($menu['content'], 'text');
					case 1: $source = D('Source_material')->where(array('pigcms_id' => $menu['fromid']))->find();
					$it_ids = unserialize($source['it_ids']);
					$images = D('Image_text')->where(array( 'pigcms_id' => array('in', $it_ids) ))->order('pigcms_id')->select();
					$return = array();
					foreach ($images as $im ) 
					{
						if (empty($im['url'])) 
						{
							$url = option('config.wap_site_url') . '/imagetxt.php?id=' . $im['pigcms_id'] . '&referer_weixin=1&sub_openid=' . $data['FromUserName'];
						}
						else 
						{
							$url = htmlspecialchars_decode($im['url']);
						}
						$return[] = array($im['title'], $im['digest'], getAttachmentUrl($im['cover_pic']), $url);
					}
					return array($return, 'news');
					case 9: import('source.class.Drp');
					$weixinInfo = D('Weixin_bind')->where('`user_name`=\'' . $data['ToUserName'] . '\'')->find();
					$store_id = $weixinInfo['store_id'];
					$subjectInfo = D('Subscribe_store')->where(array( 'openid' => $openid, 'uid' => array('>', 0) ))->find();
					$uid = ((!empty($subjectInfo['uid']) ? $subjectInfo['uid'] : 0));
					if (empty($uid)) 
					{
						$json = wexin_user_info($weixinInfo['store_id'], $openid);
						$userInfo = array();
						$userInfo['avatar'] = $json['headimgurl'];
						$userInfo['nickname'] = $json['nickname'];
						$share_visit = D('Share_visit')->where(array( 'openid' => $openid, 'store_id' => array('>', 0) ))->order('add_time DESC')->find();
						$store_id = ((!empty($share_visit['store_id']) ? $share_visit['store_id'] : $store_id));
					}
					else 
					{
						$userInfo = D('User')->where(array('uid' => $uid))->find();
						$visitor = Drp::checkID($store_id, $uid);
						if (!empty($visitor['data']['store_id'])) 
						{
							$store_id = $visitor['data']['store_id'];
						}
						else 
						{
							$share_visit = D('Share_visit')->where(array( 'openid' => $openid, 'store_id' => array('>', 0) ))->order('add_time DESC')->find();
							$store_id = ((!empty($share_visit['store_id']) ? $share_visit['store_id'] : $store_id));
						}
					}
					$fxStore = D('Store')->where(array('store_id' => $store_id))->find();
					$promote = D('Store_promote_setting')->where(array('store_id' => $store_id, 'type' => 1, 'status' => 1, 'owner' => 1))->find();
					if (empty($promote)) 
					{
						$promote = D('Store_promote_setting')->where(array('store_id' => $weixinInfo['store_id'], 'type' => 1, 'status' => 1, 'owner' => 1))->find();
					}
					$mediaResult = D('Store_media')->where(array('supplier_id' => $weixinInfo['store_id'], 'seller_id' => $store_id, 'uid' => $uid))->find();
					if (empty($uid) || empty($mediaResult['media_id']) || ($mediaResult['media_id'] && (($mediaResult['media_time'] + (60 * 60 * 24 * 28)) < time()))) 
					{
						$qrcode = M('Store')->concernRelationship(700000000, $uid, $store_id, $type = '1');
						if ($qrcode['error_code'] != 0) 
						{
							return array($qrcode['msg'], 'text');
						}
						$result = M('Store_promote_setting')->createImage($promote, $qrcode, $userInfo, $fxStore);
						if (!empty($uid)) 
						{
							if (empty($mediaResult)) 
							{
								D('Store_media')->data(array('supplier_id' => $weixinInfo['store_id'], 'seller_id' => $store_id, 'uid' => $uid, 'media_id' => $result[0], 'media_time' => time(), 'add_time' => time()))->add();
							}
							else 
							{
								D('Store_media')->data(array('media_id' => $result[0], 'media_time' => time()))->where(array('supplier_id' => $weixinInfo['store_id'], 'seller_id' => $store_id, 'uid' => $uid))->save();
							}
						}
						$token_data = M('Weixin_bind')->get_access_token($weixinInfo['store_id']);
						if ($token_data['errcode'] == 0) 
						{
							import('source.class.Http');
							$local_path = PIGCMS_PATH . $result[0];
							$upload = Http::curlPost('http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $token_data['access_token'] . '&type=image', array('media' => '@' . $local_path));
							if ($upload['errcode'] == 0) 
							{
								$media_id = $upload['media_id'];
							}
							switch ($menu['type']) 
							{
							}
							else 
							{
								return array('微信响应超时，请重新获取', 'text');
							}
						}
						return array($media_id, 'image');
					}
					$token_data = M('Weixin_bind')->get_access_token($weixinInfo['store_id']);
					if ($token_data['errcode'] == 0) 
					{
						import('source.class.Http');
						$local_path = PIGCMS_PATH . $mediaResult['media_id'];
						$upload = Http::curlPost('http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $token_data['access_token'] . '&type=image', array('media' => '@' . $local_path));
						if ($upload['errcode'] == 0) 
						{
							$media_id = $upload['media_id'];
						}
						switch ($menu['type']) 
						{
						}
						else 
						{
							return array('微信响应超时，请重新获取', 'text');
						}
					}
					return array($media_id, 'image');
				}
			}
			return array('系统暂时不能给出对应的回复', 'text');
			case 'SUBSCRIBE': return SUBSCRIBE($id, $data, $weixin_bind['store_id']);
			case 'UNSUBSCRIBE': $openid = $data['FromUserName'];
			$where = array();
			$where['openid'] = $openid;
			$where['subscribe_time'] = array('>', 0);
			D('Subscribe_store')->where($where)->data(array('is_leave' => '1', 'leave_time' => time()))->save();
			return array('BYE-BYE', 'text');
			case 'LOCATION': $courier_info = D('Store_physical_courier')->where(array('openid' => $data['FromUserName']))->find();
			if (!empty($courier_info) && (30 <= $data['CreateTime'] - $courier_info['location_time'])) 
			{
				D('Store_physical_courier')->where(array('openid' => $data['FromUserName']))->data(array('long' => $data['Longitude'], 'lat' => $data['Latitude'], 'location_time' => $data['CreateTime']))->save();
			}
			break;
		}
	}
	else if ($data['MsgType'] == 'text') 
	{
		$content = $data['Content'];
		if ($content == '配送员') 
		{
			$openid = $data['FromUserName'];
			$courier_info = D('Store_physical_courier')->where(array('openid' => $openid))->find();
			if (empty($courier_info['avatar'])) 
			{
				return array('请先补全您的配送信息', 'text');
			}
			$title = '查看 ' . $courier_info['name'] . ' 的配送包裹';
			$url = option('config.wap_site_url') . '/courier.php?openid=' . $openid . '&sub_openid=' . $openid;
			$return[] = array($title, '', $courier_info['avatar'], $url);
			return array($return, 'news');
		}
		$storeInfo = D('Store')->where(array('store_id' => $weixin_bind['store_id']))->find();
		if (!empty($storeInfo) && ($activity = D('Activity_spread')->where(array('keyword' => $content, 'token' => $storeInfo['pigcmsToken']))->find())) 
		{
			$url = M('Activity')->createUrl($activity, $activity['model'], true);
			$return[] = array('[活动]' . $activity['title'], $activity['info'], $activity['image'], $url);
			return array($return, 'news');
		}
		if ($keyword = D('Keyword')->where(array('content' => $content, 'store_id' => $weixin_bind['store_id']))->find()) 
		{
			return special_keyword($keyword['from_id'], $weixin_bind['store_id'], $data['FromUserName']);
		}
		if (($weixin_bind['service_type_info'] == 2) && ($weixin_bind['verify_type_info'] != '-1')) 
		{
			return array(0, 'transfer_customer_service');
		}
		return array('系统暂时不能找到[' . $content . ']关键词对应的回复', 'text');
	}
	else if ($data['MsgType'] == 'location') 
	{
	}
	return false;
}
function SUBSCRIBE($id, $data, $supplier_id) 
{
	if (strpos($id, 'qrscene_') !== false) 
	{
		$ids = explode('_', $id);
		$id = array_pop($ids);
	}
	$openid = $data['FromUserName'];
	if ((100000000 < $id) && ($id < 200000000)) 
	{
		$id = $id - 100000000;
	}
	else if ((200000000 < $id) && ($id < 300000000)) 
	{
		$id = $id - 200000000;
		drp_subscribe_store_other($openid, $supplier_id, $id, $supplier_id, 0);
		return drp_subscribe_store($id, $openid, $supplier_id);
	}
	else if ((300000000 < $id) && ($id < 400000000)) 
	{
		$id = $id - 300000000;
		drp_subscribe_store_other($openid, $id, '', $supplier_id, 0);
		return bind_dispatch($id, $openid);
	}
	else if ((400000000 < $id) && ($id < 410000000)) 
	{
		$id = $id - 400000000;
		$store_info = D('Store')->where(array('store_id' => $id))->find();
		if (empty($store_info)) 
		{
			return array('参数错误，店铺不存在', 'text');
		}
		if ($store_info['openid']) 
		{
			return array('您店铺已经绑定过微信账号，请勿重复绑定', 'text');
		}
		D('Store')->where(array('store_id' => $id))->data(array('openid' => $openid))->save();
		return array('店铺绑定微信账号成功', 'text');
	}
	else if ((410000000 < $id) && ($id < 420000000)) 
	{
		$id = $id - 410000000;
	}
	else if ((500000000 < $id) && ($id < 600000000)) 
	{
		$id = $id - 500000000;
		if ($activity = D('Activity_spread')->where(array('pigcms_id' => $id))->find()) 
		{
			drp_subscribe_store_other($openid, $supplier_id, $id, $supplier_id, 0);
			$url = M('Activity')->createUrl($activity, $activity['model'], true);
			$return[] = array('[活动]' . $activity['title'], $activity['info'], $activity['image'], $url);
			return array($return, 'news');
		}
		return array('未发现活动', 'text');
	}
	else if ((600000000 < $id) && ($id < 700000000)) 
	{
		$id = $id - 600000000;
		return subscribe_discount($openid, $id, $supplier_id);
	}
	else if ((700000000 < $id) && ($id < 800000000)) 
	{
		$id = $id - 700000000;
		return prompoteReply($openid, $id, $supplier_id);
	}
	else if ((800000000 < $id) && ($id < 900000000)) 
	{
		$id = $id - 800000000;
		return activity_img_text($openid, $id);
	}
	else 
	{
		return drp_subscribe_store_other($openid, $id, '', $supplier_id);
	}
}
function activity_img_text($openid, $id, $supplier_id) 
{
	$prompoteInfo = D('Concern_relationship')->where(array('pigcms_id' => $id))->find();
	$store_id = $prompoteInfo['store_id'];
	if (($prompoteInfo['act_type'] == 'lottery') || ($prompoteInfo['act_type'] == 'yousetdiscount') || ($prompoteInfo['act_type'] == 'helping')) 
	{
		$actInfo = D(ucfirst($prompoteInfo['act_type']))->where(array('id' => $prompoteInfo['act_id']))->find();
	}
	else 
	{
		$actInfo = D(ucfirst($prompoteInfo['act_type']))->where(array('pigcms_id' => $prompoteInfo['act_id']))->find();
	}
	if (empty($actInfo)) 
	{
		return array('活动不存在或已失效', 'text');
	}
	drp_subscribe_store_other($openid, $store_id, 0, $supplier_id, 0);
	if (!empty($actInfo['store_id'])) 
	{
		$store_id = $actInfo['store_id'];
	}
	$storeInfo = D('Store')->field('store_id,name,root_supplier_id,setting_fans_forever')->where(array('store_id' => $store_id))->find();
	$json = wexin_user_info($supplier_id, $openid);
	$tpl = '尊敬的 {$nickname}, 感谢您关注 {$store}，点击进入活动。';
	$image = STATIC_URL . 'images/' . strtolower($prompoteInfo['act_type']) . '.png';
	$return = array();
	if (strtolower($prompoteInfo['act_type']) == 'bargain') 
	{
		$image = STATIC_URL . 'images/bargain.png';
		if (empty($prompoteInfo['help_uid'])) 
		{
			$url = option('config.wap_site_url') . '/bargain.php?action=detail&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'];
		}
		else 
		{
			$url = option('config.wap_site_url') . '/bargain.php?action=detail&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'] . '&friend=' . $prompoteInfo['help_uid'];
		}
	}
	else if (strtolower($prompoteInfo['act_type']) == 'seckill') 
	{
		$image = STATIC_URL . 'images/seckill.png';
		$url = option('config.wap_site_url') . '/seckill.php?seckill_id=' . $prompoteInfo['act_id'];
	}
	else if (strtolower($prompoteInfo['act_type']) == 'lottery') 
	{
		$image = STATIC_URL . 'images/lottery/' . $actInfo['type'] . '.jpg';
		$url = option('config.wap_site_url') . '/lottery.php?action=detail&id=' . $prompoteInfo['act_id'];
	}
	else if (strtolower($prompoteInfo['act_type']) == 'helping') 
	{
		$image = STATIC_URL . 'images/helping.jpg';
		if (empty($prompoteInfo['help_uid'])) 
		{
			$url = option('config.wap_site_url') . '/helping.php?action=detail&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'];
		}
		else 
		{
			$url = option('config.wap_site_url') . '/helping.php?action=detail&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'] . '&share_key=' . $prompoteInfo['help_uid'];
		}
	}
	else if (strtolower($prompoteInfo['act_type']) == 'cutprice') 
	{
		$image = STATIC_URL . 'images/' . strtolower($prompoteInfo['act_type']) . '.jpg';
		$url = option('config.wap_site_url') . '/cutprice.php?action=detail&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'];
	}
	else if (strtolower($prompoteInfo['act_type']) == 'yousetdiscount') 
	{
		$image = STATIC_URL . 'images/wxpic.jpg';
		$url = option('config.wap_site_url') . '/yousetdiscount.php?action=index&id=' . $prompoteInfo['act_id'] . '&store_id=' . $actInfo['store_id'];
		if (!empty($prompoteInfo['help_uid']) && ($yuser = D('Yousetdiscount_users')->where(array('yid' => $prompoteInfo['act_id'], 'uid' => $prompoteInfo['help_uid']))->find())) 
		{
			$url .= '&share_key=' . $yuser['share_key'];
		}
	}
	$content = str_replace(array('{$nickname}', '{$store}'), array($json['nickname'], $storeInfo['name']), $tpl);
	$return[] = array($content, '', $image, $url);
	return array($return, 'news');
}
function prompoteReply($openid, $id, $supplier_id) 
{
	$prompoteInfo = D('Concern_relationship')->where(array('pigcms_id' => $id))->find();
	drp_subscribe_store_other($openid, $prompoteInfo['store_id'], '', $supplier_id, 0);
	$store_info = D('Store')->where(array('store_id' => $prompoteInfo['store_id']))->find();
	$store_id = $prompoteInfo['store_id'];
	$qrcode_result = D('Qrcode_record')->where(array('store_id' => $prompoteInfo['store_id'], 'openid' => $openid))->find();
	if ($qrcode_result) 
	{
		D('Qrcode_record')->where(array('store_id' => $prompoteInfo['store_id'], 'openid' => $openid))->data(array('record_time' => time()))->save();
	}
	else 
	{
		D('Qrcode_record')->data(array('record_time' => time(), 'store_id' => $prompoteInfo['store_id'], 'openid' => $openid))->add();
	}
	$json = wexin_user_info($supplier_id, $openid);
	$supplier_store = D('Store')->field('store_id,name,uid,canal_qrcode_tpl,canal_qrcode_img')->where(array('store_id' => $supplier_id))->find();
	$supplier_store['canal_qrcode_tpl'] = (!empty($supplier_store['canal_qrcode_tpl']) ? $supplier_store['canal_qrcode_tpl'] : '尊敬的 {$nickname}, 感谢您关注 {$store}，点击进入店铺。');
	if (empty($supplier_store['canal_qrcode_tpl'])) 
	{
		$supplier_store['canal_qrcode_tpl'] = '尊敬的 {$nickname}, 感谢您关注 {$store}，点击进入店铺。';
	}
	if (empty($supplier_store['canal_qrcode_img'])) 
	{
		$supplier_store['canal_qrcode_img'] = getAttachmentUrl('images/drp_ad_01.png');
	}
	$return = array();
	$url = option('config.wap_site_url') . '/home.php?id=' . $prompoteInfo['store_id'] . '';
	$content = str_replace(array('{$nickname}', '{$store}'), array($json['nickname'], $store_info['name']), $supplier_store['canal_qrcode_tpl']);
	$return[] = array($content, '', $supplier_store['canal_qrcode_img'], $url);
	if (!empty($storeInfo['setting_fans_forever'])) 
	{
		$data = array();
		$where = array();
		if ($prompoteInfo['type'] == 2) 
		{
			$data['uid'] = $prompoteInfo['uid'];
			$where['uid'] = $prompoteInfo['uid'];
		}
		$data['store_id'] = $store_id;
		$data['openid'] = $openid;
		$where['openid'] = $openid;
		$fans_forever = D('Store_fans_forever')->where($where)->find();
		if (empty($fans_forever)) 
		{
			$data['add_time'] = time();
			D('Store_fans_forever')->data($data)->add();
		}
		else 
		{
			D('Store_fans_forever')->where($where)->data($data)->save();
		}
	}
	else if ($prompoteInfo['type'] == 1) 
	{
		$data = array();
		$data['openid'] = $openid;
		$data['store_id'] = $store_id;
		$data['supplier_id'] = $prompoteInfo['supplier_id'];
		$data['type'] = 1;
		$data['code'] = 'qrcode';
		$data['visited'] = 0;
		$data['add_time'] = time();
		$where = array();
		$where['openid'] = $openid;
		$where['store_id'] = $store_id;
		$share = D('Share_visit')->where($where)->find();
		if (empty($share)) 
		{
			D('Share_visit')->data($data)->add();
		}
		else 
		{
			D('Share_visit')->where(array('pigcms_id' => $share['pigcms_id']))->data(array('visited' => 0, 'add_time' => time()))->save();
		}
	}
	return array($return, 'news');
}
function weixin_scan($id, $data, $supplier_id) 
{
	$openid = $data['FromUserName'];
	if (strpos($id, 'limit_scene_') !== false) 
	{
		$id = str_replace('limit_scene_', '', $id);
		$arr = explode('_', $id);
		$type = array_pop($arr);
	}
	if ((100000000 < $id) && ($id < 200000000)) 
	{
	}
	else if ((200000000 < $id) && ($id < 300000000)) 
	{
		$id = $id - 200000000;
		drp_subscribe_store_other($openid, $supplier_id, $id, $supplier_id);
	}
	else if ((300000000 < $id) && ($id < 400000000)) 
	{
		$id = $id - 300000000;
		return bind_dispatch($id, $openid);
	}
	else if ((400000000 < $id) && ($id < 410000000)) 
	{
		$id = $id - 400000000;
		$store_info = D('Store')->where(array('store_id' => $id))->find();
		if (empty($store_info)) 
		{
			return array('参数错误，店铺不存在', 'text');
		}
		if ($store_info['openid']) 
		{
			return array('您店铺已经绑定过微信账号，请勿重复绑定', 'text');
		}
		D('Store')->where(array('store_id' => $id))->data(array('openid' => $openid))->save();
		return array('店铺绑定微信账号成功', 'text');
	}
	else if ((410000000 < $id) && ($id < 420000000)) 
	{
		$id = $id - 410000000;
	}
	else if ((500000000 < $id) && ($id < 600000000)) 
	{
		$id = $id - 500000000;
		if ($activity = D('Activity_spread')->where(array('pigcms_id' => $id))->find()) 
		{
			drp_subscribe_store_other($openid, $supplier_id, $id, $supplier_id, 0);
			$url = M('Activity')->createUrl($activity, $activity['model'], true);
			$return[] = array('[活动]' . $activity['title'], $activity['info'], $activity['image'], $url);
			return array($return, 'news');
		}
		return array('未发现活动', 'text');
	}
	else if ((600000000 < $id) && ($id < 700000000)) 
	{
		$id = $id - 600000000;
		return subscribe_discount($openid, $id, $supplier_id);
	}
	else if ((700000000 < $id) && ($id < 800000000)) 
	{
		$id = $id - 700000000;
		return prompotereply($openid, $id, $supplier_id);
	}
	else if ((800000000 < $id) && ($id < 900000000)) 
	{
		$id = $id - 800000000;
		return activity_img_text($openid, $id, $supplier_id);
	}
}
function subscribe_discount($openid, $id, $supplier_id) 
{
	$store_product = D('Fx_store_product')->where(array('id' => $id))->find();
	$store_id = $store_product['store_id'];
	$fxInfo = D('Store')->field('name,setting_fans_forever')->where(array('store_id' => $store_id))->find();
	if (!empty($fxInfo['setting_fans_forever'])) 
	{
		$data = array();
		$where = array();
		if (!empty($prompoteInfo['uid'])) 
		{
			$data['uid'] = $prompoteInfo['uid'];
			$where['uid'] = $prompoteInfo['uid'];
		}
		$data['store_id'] = $store_id;
		$data['openid'] = $openid;
		$where['openid'] = $openid;
		$fans_forever = D('Store_fans_forever')->where($where)->find();
		if (empty($fans_forever)) 
		{
			$data['add_time'] = time();
			D('Store_fans_forever')->data($data)->add();
		}
		else 
		{
			D('Store_fans_forever')->where($where)->data($data)->save();
		}
	}
	else 
	{
		$data = array();
		$data['openid'] = $openid;
		$data['store_id'] = $store_id;
		$data['supplier_id'] = $prompoteInfo['supplier_id'];
		$data['type'] = 2;
		$data['code'] = 'product';
		$data['visited'] = 0;
		$data['add_time'] = time();
		$where = array();
		$where['openid'] = $openid;
		$where['store_id'] = $store_id;
		$share = D('Share_visit')->where($where)->find();
		if (empty($share)) 
		{
			D('Share_visit')->data($data)->add();
		}
		else 
		{
			D('Share_visit')->where(array('pigcms_id' => $share['pigcms_id']))->data(array('visited' => 0, 'add_time' => time()))->save();
		}
	}
	$text = '感谢您关注 “' . $fxInfo['name'] . '”，点击购买商品。';
	$url = option('config.wap_site_url') . '/good.php?id=' . $store_product['product_id'] . '&store_id=' . $store_product['store_id'] . '&referer_weixin=1';
	drp_subscribe_store_other($openid, $store_product['store_id'], '', $supplier_id, 0);
	return array('<a href="' . $url . '">' . $text . '</a>', 'text');
}
function reply_qcode($openid, $uid, $store_id, $type) 
{
	$where = array('store_id' => $store_id, 'openid' => $openid);
	$record = D('Qrcode_record')->where($where)->find();
	if (empty($record)) 
	{
		$data = array('store_id' => $store_id, 'openid' => $openid, 'record_time' => time());
		D('Qrcode_record')->data($data)->add();
	}
	else 
	{
		D('Qrcode_record')->where($where)->data(array('record_time' => time()))->save();
	}
	$store_info = D('Store')->where(array('store_id' => $store_id))->find();
	if (0 < $store_info['drp_level']) 
	{
		$supplier_root = D('Store')->field('root_supplier_id')->where(array('store_id' => $store_info['store_id']))->find();
		$root_supplier_id = $supplier_root['root_supplier_id'];
	}
	else if ($store_info['drp_level'] == 0) 
	{
		$root_supplier_id = $store_info['store_id'];
	}
	if ($type == 'pro') 
	{
		$subscribe = D('Subscribe_store')->where(array('store_id' => $root_supplier_id, 'uid' => $uid))->find();
		if ($subscribe) 
		{
			D('Subscribe_store')->where(array('sub_id' => $subscribe['sub_id']))->data(array('subscribe_time' => time(), 'user_subscribe_time' => time(), 'is_leave' => 0))->save();
		}
		else 
		{
			D('Subscribe_store')->data(array('openid' => $openid, 'store_id' => $root_supplier_id, 'uid' => $uid, 'subscribe_time' => time(), 'user_subscribe_time' => time(), 'is_leave' => 0))->add();
		}
	}
	$json = wexin_user_info($root_supplier_id, $openid);
	$supplier_store = D('Store')->field('store_id,name,uid,canal_qrcode_tpl,canal_qrcode_img')->where(array('store_id' => $root_supplier_id))->find();
	$supplier_store['canal_qrcode_tpl'] = (!empty($supplier_store['canal_qrcode_tpl']) ? $supplier_store['canal_qrcode_tpl'] : '尊敬的 {$nickname}, 感谢您关注 {$store}，点击进入店铺。');
	if (empty($supplier_store['canal_qrcode_tpl'])) 
	{
		$supplier_store['canal_qrcode_tpl'] = '尊敬的 {$nickname}, 感谢您关注 {$store}，点击进入店铺。';
	}
	if (empty($supplier_store['canal_qrcode_img'])) 
	{
		$supplier_store['canal_qrcode_img'] = getAttachmentUrl('images/drp_ad_01.png');
	}
	$return = array();
	$url = option('config.wap_site_url') . '/home.php?id=' . $store_id . '';
	if ($type == 'tg') 
	{
		$url = option('config.wap_site_url') . '/home.php?id=' . $store_id . '&subStore=1';
	}
	else if ($type == 'pro') 
	{
		$supplier_store['canal_qrcode_tpl'] = '尊敬的 {$nickname}, 感谢您关注 {$store}，点击查看商品。';
		$url = option('config.wap_site_url') . '/good.php?id=' . $type . '&store_id=' . $store_id;
	}
	$content = str_replace(array('{$nickname}', '{$store}'), array($json['nickname'], $store_info['name']), $supplier_store['canal_qrcode_tpl']);
	$return[] = array($content, '', $supplier_store['canal_qrcode_img'], $url);
	return array($return, 'news');
}
function bind_dispatch($id, $openid) 
{
	if (D('Store_physical_courier')->where(array('store_id' => $id, 'openid' => $openid))->find()) 
	{
		return array('您已经绑定过配送员，请不要重新绑定', 'text');
	}
	D('Store_physical_courier')->data(array('store_id' => $id, 'openid' => $openid, 'add_time' => time()))->add();
	return array('绑定配送员成功，请前往补全配送员信息', 'text');
}
function drp_subscribe_store($uid, $openid, $store_id) 
{
	$drp_subscribe = D('Store')->field('open_drp_subscribe_auto')->where(array('store_id' => $store_id))->find();
	$store = D('Store')->field('*')->where(array('store_id' => $store_id))->find();
	$root_supplier_id = M('Store_supplier')->getSupplierId($store_id);
	$seller_count = M('Store')->seller_count($where, $root_supplier_id);
	$temp_arr = D('')->table('Store as s')->join('User as u ON s.uid=u.uid', 'LEFT')->join('Package as p ON u.package_id=p.pigcms_id', 'LEFT')->where('`s`.`store_id`=' . $root_supplier_id)->field('`u`.uid,`s`.store_id,`s`.name,`s`.openid,`u`.package_id,`p`.distributor_nums ')->find();
	$p_distributor_nums = $temp_arr['distributor_nums'];
	$tmp_flag = true;
	if (!empty($p_distributor_nums)) 
	{
		if ($p_distributor_nums != '0') 
		{
			if ($p_distributor_nums <= $seller_count) 
			{
				$tmp_flag = false;
				if ($temp_arr['openid']) 
				{
					import('source.class.ShopNotice');
					ShopNotice::fxsLimitResultNotice($temp_arr['store_id'], $temp_arr['openid'], $temp_arr['name']);
				}
			}
		}
	}
	if (!empty($drp_subscribe) && $tmp_flag) 
	{
		$common_data = M('Common_data');
		$sale_category = M('Sale_category');
		$store_supplier = M('Store_supplier');
		$user = D('User')->field('uid,nickname,avatar')->where(array('uid' => $uid))->find();
		$user['nickname'] = (!empty($user['nickname']) ? $user['nickname'] : '会员');
		$is_subscribed = D('Subscribe_store')->field('sub_id,uid,subscribe_time')->where(array('uid' => $uid, 'openid' => $openid))->find();
		if (empty($is_subscribed)) 
		{
			D('Subscribe_store')->data(array('uid' => $uid, 'openid' => $openid, 'store_id' => $store_id, 'subscribe_time' => time()))->add();
		}
		else 
		{
			if (($is_subscribed['subscribe_time'] == 0) || ($is_subscribed['uid'] == 0)) 
			{
				D('Subscribe_store')->data(array('uid' => $uid, 'subscribe_time' => time()))->where(array('openid' => $openid, 'store_id' => $store_id))->save();
			}
			else 
			{
				D('Subscribe_store')->data(array('is_leave' => 0, 'leave_time' => 0))->where(array('openid' => $openid, 'store_id' => $store_id))->save();
			}
		}
		if (!empty($store['open_drp_subscribe_auto'])) 
		{
			$supplier_id = $store_id;
			$name = ((!empty($user['nickname']) ? $user['nickname'] : $store['name'] . '分店'));
			$linkname = $user['nickname'];
			$avatar = $user['avatar'];
			$drp_level = $store['drp_level'] + 1;
			$data = array();
			$data['uid'] = $uid;
			$data['name'] = $name;
			$data['sale_category_id'] = $store['sale_category_id'];
			$data['sale_category_fid'] = $store['sale_category_fid'];
			$data['linkman'] = $linkname;
			$data['tel'] = '';
			$data['status'] = 1;
			$data['qq'] = '';
			$data['drp_supplier_id'] = $supplier_id;
			$data['date_added'] = time();
			$data['drp_level'] = $drp_level;
			$data['logo'] = $avatar;
			$data['open_nav'] = $store['open_nav'];
			$data['bind_weixin'] = 0;
			$data['open_drp_diy_store'] = 0;
			$data['drp_diy_store'] = 0;
			$data['root_supplier_id'] = $root_supplier_id;
			if (!empty($store['open_drp_approve'])) 
			{
				$data['drp_approve'] = 0;
			}
			if (M('Drp_team')->checkDrpTeam($supplier_id, true)) 
			{
				$first_seller_id = M('Store_supplier')->getFirstSeller($supplier_id);
				$first_seller = D('Store')->field('drp_team_id')->where(array('store_id' => $first_seller_id))->find();
				if (!empty($first_seller['drp_team_id'])) 
				{
					$data['drp_team_id'] = $first_seller['drp_team_id'];
				}
			}
			$store['drp_subscribe_img'] = (!empty($store['drp_subscribe_img']) ? $store['drp_subscribe_img'] : getAttachmentUrl('images/drp_ad_01.png'));
			$result = M('Store')->create($data);
			if (!empty($result['err_code'])) 
			{
				$common_data->setStoreQty();
				$store_id = $result['err_msg']['store_id'];
				if (!empty($data['drp_team_id'])) 
				{
					M('Drp_team')->setMembersInc($data['drp_team_id']);
				}
				M('User')->setStoreInc($uid);
				M('User')->setSeller($uid, 1);
				$sale_category->setStoreInc($store['sale_category_id']);
				$sale_category->setStoreInc($store['sale_category_fid']);
				$current_seller = $store_supplier->getSeller(array('seller_id' => $store_id));
				if ($current_seller['supplier_id'] != $supplier_id) 
				{
					$seller = $store_supplier->getSeller(array('seller_id' => $supplier_id));
					if (empty($seller['type'])) 
					{
						$seller['supply_chain'] = 0;
						$seller['level'] = 0;
					}
					$seller['supply_chain'] = (!empty($seller['supply_chain']) ? $seller['supply_chain'] : 0);
					$seller['level'] = (!empty($seller['level']) ? $seller['level'] : 0);
					$supply_chain = ((!empty($supplier_id) ? $seller['supply_chain'] . ',' . $supplier_id : 0));
					$level = $seller['level'] + 1;
					$data = array();
					$data['supplier_id'] = $supplier_id;
					$data['seller_id'] = $store_id;
					$data['supply_chain'] = $supply_chain;
					$data['level'] = $level;
					$data['type'] = 1;
					$data['root_supplier_id'] = $root_supplier_id;
					$store_supplier->add($data);
				}
				$common_data->setDrpSellerQty();
				$return = array();
				$store['drp_subscribe_tpl'] = (!empty($store['drp_subscribe_tpl']) ? $store['drp_subscribe_tpl'] : '尊敬的 {$nickname}, 您已成为 {$store} 第 {$num} 位分销商，点击管理店铺。');
				if (stripos($store['drp_subscribe_tpl'], '{$num}') !== false) 
				{
					$sellers = $store_supplier->getSubSellers($supplier_id);
					$seller_num = count($sellers);
					$content = str_replace(array('{$nickname}', '{$store}', '{$num}'), array($user['nickname'], $store['name'], $seller_num), $store['drp_subscribe_tpl']);
				}
				else if (preg_match('/\\{\\$num=(\\d+)\\}/i', $store['drp_subscribe_tpl'])) 
				{
					$sellers = $store_supplier->getSubSellers($supplier_id);
					global $global_seller_num;
					$global_seller_num = count($sellers);
					$content = str_replace(array('{$nickname}', '{$store}'), array($user['nickname'], $store['name']), $store['drp_subscribe_tpl']);
					$content = preg_replace_callback('/\\{\\$num=(\\d+)\\}/i', function($num) 
					{
						global $global_seller_num;
						$num[1] = (!empty($num[1]) ? $num[1] : 0);
						return $num[1] + $global_seller_num;
					}
					, $content);
				}
				import('source.class.Points');
				Points::drpStore($uid, $supplier_id, $store_id);
				if (!D('Store_user_data')->where(array('store_id' => $supplier_id, 'uid' => $uid))->count('pigcms_id')) 
				{
					D('Store_user_data')->data(array('store_id' => $supplier_id, 'uid' => $uid))->add();
				}
				$return[] = array($content, '', $store['drp_subscribe_img'], option('config.wap_site_url') . '/home.php?id=' . $store_id . '&sub_openid=' . $openid);
				return array($return, 'news');
			}
			$return = array();
			$content = '感谢您的关注，点击访问店铺！';
			$return[] = array($content, '', $store['drp_subscribe_img'], option('config.wap_site_url') . '/home.php?id=' . $store_id . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
		if (!empty($store['open_drp_subscribe'])) 
		{
			if (empty($store['reg_drp_subscribe_tpl'])) 
			{
				$store['reg_drp_subscribe_tpl'] = '尊敬的 {$nickname}, 感谢您关注 {$store} 公众号，点击申请分销。';
			}
			if (empty($store['reg_drp_subscribe_img'])) 
			{
				$store['reg_drp_subscribe_img'] = getAttachmentUrl('images/drp_ad_01.png');
			}
			$return = array();
			$content = str_replace(array('{$nickname}', '{$store}'), array($user['nickname'], $store['name']), $store['reg_drp_subscribe_tpl']);
			$return[] = array($content, '', $store['reg_drp_subscribe_img'], option('config.wap_site_url') . '/drp_register.php?id=' . $store_id . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
	}
}
function drp_subscribe_store_other($openid, $store_id = 0, $uid = 0, $supplier_id = 0, $return = 1) 
{
	$where = array();
	$where['openid'] = $openid;
	$where['store_id'] = ($store_id ? $store_id : 0);
	$is_subscribed = D('Subscribe_store')->where($where)->find();
	if ($is_subscribed && ($is_subscribed['is_leave'] == 1)) 
	{
		D('Subscribe_store')->where(array('sub_id' => $is_subscribed['sub_id']))->data(array('subscribe_time' => time(), 'user_subscribe_time' => time(), 'is_leave' => 0, 'leave_time' => 0))->save();
	}
	else if (empty($is_subscribed)) 
	{
		D('Subscribe_store')->data(array('openid' => $openid, 'store_id' => $store_id, 'uid' => $uid, 'subscribe_time' => time(), 'user_subscribe_time' => time(), 'is_leave' => 0))->add();
	}
	if ($is_subscribed && ($is_subscribed['is_leave'] == 0)) 
	{
		if ($uid && (($is_subscribed['subscribe_time'] == 0) || ($is_subscribed['uid'] == 0))) 
		{
			D('Subscribe_store')->data(array('uid' => $uid, 'subscribe_time' => time()))->where(array('openid' => $openid, 'store_id' => $store_id))->save();
			import('source.class.Points');
			Points::subscribe($is_subscribed['uid'], $supplier_id, $store_id);
		}
		else if (($is_subscribed['subscribe_time'] == 0) && $is_subscribed['uid']) 
		{
			D('Subscribe_store')->data(array('subscribe_time' => time()))->where(array('openid' => $openid, 'store_id' => $store_id, 'subscribe_time' => 0))->save();
			import('source.class.Points');
			Points::subscribe($is_subscribed['uid'], $supplier_id, $store_id);
		}
		else 
		{
			D('Subscribe_store')->data(array('is_leave' => 0, 'leave_time' => 0))->where(array('openid' => $openid, 'store_id' => $store_id))->save();
		}
	}
	if ($return) 
	{
		$rule = D('Rule')->where(array('store_id' => $supplier_id, 'type' => 1))->find();
		if ($rule) 
		{
			return special_keyword($rule['pigcms_id'], $supplier_id, $openid);
		}
		return array('感谢您的关注，我们将竭诚为您服务！', 'text');
	}
}
function get_access_token($auth_code) 
{
	import('source.class.Http');
	$url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
	$data = array('component_appid' => option('config.wx_appid'), 'component_appsecret' => option('config.wx_appsecret'), 'component_verify_ticket' => option('config.wx_componentverifyticket'));
	$result = Http::curlPost($url, json_encode($data));
	if ($result['errcode']) 
	{
		return false;
	}
	$url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $result['component_access_token'];
	$data = array('component_appid' => option('config.wx_appid'), 'authorization_code' => $auth_code);
	$result1 = Http::curlPost($url, json_encode($data));
	if ($result1['errcode']) 
	{
		return false;
	}
	return $result1['authorization_info']['authorizer_access_token'];
}
function special_keyword($rule_id, $store_id, $openid) 
{
	$reply_relation = D('Reply_relation')->where(array('rid' => $rule_id, 'store_id' => $store_id))->select();
	$index = array_rand($reply_relation);
	$reply = $reply_relation[$index];
	switch ($reply['type']) 
	{
		case 0: $tail = '';
		if ($reply_tail = D('Reply_tail')->where(array('store_id' => $store_id))->find()) 
		{
			if ($reply_tail['is_open']) 
			{
				$tail = ' 『' . $reply_tail['content'] . '』';
			}
		}
		$text = D('Text')->where(array('pigcms_id' => $reply['cid']))->find();
		return array($text['content'] . $tail, 'text');
		case 1: $source = D('Source_material')->where(array('pigcms_id' => $reply['cid']))->find();
		$it_ids = unserialize($source['it_ids']);
		$images = D('Image_text')->where(array( 'pigcms_id' => array('in', $it_ids) ))->order('pigcms_id')->select();
		$return = array();
		foreach ($images as $im ) 
		{
			if (empty($im['url'])) 
			{
				$url = option('config.wap_site_url') . '/imagetxt.php?id=' . $im['pigcms_id'] . '&sub_openid=' . $openid;
			}
			else 
			{
				$url = htmlspecialchars_decode($im['url']) . '&sub_openid=' . $openid;
			}
			$return[] = array($im['title'], $im['digest'], getAttachmentUrl($im['cover_pic']), $url);
		}
		return array($return, 'news');
		case 2: break;
		case 3: if ($product = D('Product')->where(array('store_id' => $reply['store_id'], 'product_id' => $reply['cid']))->find()) 
		{
			$return[] = array($product['name'], $product['image'], option('config.wap_site_url') . '/good.php?id=' . $product['product_id'] . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
		break;
		case 4: if ($group = D('Product_group')->where(array('store_id' => $reply['store_id'], 'group_id' => $reply['cid']))->find()) 
		{
			$return[] = array($group['group_name'], '', '', option('config.wap_site_url') . '/goodcat.php?id=' . $group['group_id'] . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
		break;
		case 5: if ($page = D('Wei_page')->where(array('store_id' => $reply['store_id'], 'page_id' => $reply['cid']))->find()) 
		{
			$return[] = array($page['page_name'], '', '', option('config.wap_site_url') . '/page.php?id=' . $page['page_id'] . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
		break;
		case 6: if ($category = D('Wei_page_category')->where(array('store_id' => $reply['store_id'], 'cat_id' => $reply['cid']))->find()) 
		{
			$return[] = array($category['cat_name'], '', '', option('config.wap_site_url') . '/pagecat.php?id=' . $category['cat_id'] . '&sub_openid=' . $openid);
			return array($return, 'news');
		}
		break;
		case 7: $return[] = array('店铺主页', '', '', option('config.wap_site_url') . '/home.php?id=' . $reply['cid'] . '&sub_openid=' . $openid);
		return array($return, 'news');
		case 8: $return[] = array('会员主页', '', '', option('config.wap_site_url') . '/ucenter.php?id=' . $reply['cid'] . '&sub_openid=' . $openid);
		return array($return, 'news');
	}
}
function wexin_user_info($store_id, $openid) 
{
	$data = S('USER_INFO_' . $openid);
	if (empty($data)) 
	{
		$http = new Http();
		$token_data = M('Weixin_bind')->get_access_token($store_id);
		if ($token_data['errcode'] == 0) 
		{
			$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token_data['access_token'] . '&openid=' . $openid . '&lang=zh_CN';
			$res = $http->curlGet($url);
			$data = json_decode($res, true);
			S('USER_INFO_' . $openid, $data);
		}
	}
	return $data;
}